﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : MultiServerEngine | MasterServer | AccountLoginResponseHandler.cs
// //  Created : 2016 - 02 - 16 20:53
// //  Modified: 2016 - 02 - 20 12:33
// //  ********************************************************************************

using System;
using ExitGames.Logging;
using Photon.SocketServer;
using ServerFramework.Implementation.Client;
using ServerFramework.Implementation.Handler;
using ServerFramework.Implementation.Telegram;
using ServerFramework.Interfaces.Client;
using ServerFramework.Interfaces.Server;
using ServerFramework.Interfaces.Telegram;
using TypeDefs;

namespace MasterServer.Handler.Response
{
    public class AccountLoginResponseHandler : ServerTelegramHandler
    {
        private IClientPeerRegistry<IClientPeer> ClientPeerRegistry { get; }

        public override TelegramHandlerTypes HandlerType => TelegramHandlerTypes.Response;
        public override byte Code => (byte) OperationCodes.Login;
        public override int? SubCode => (int?) OperationSubCodes.LoginAccount;

        public AccountLoginResponseHandler(ILogger logger, IClientPeerRegistry<IClientPeer> clientPeerRegistry)
            : base(logger)
        {
            ClientPeerRegistry = clientPeerRegistry;
        }

        public override bool HandleTelegram(ITelegram telegram, IServerPeer serverPeer)
        {
            Logger.InfoFormat("Received response for client {0}", telegram.Parameters[(byte) ParameterCodes.PeerId]);

            ResponseTelegram response = telegram as ResponseTelegram;

            Guid guid = Guid.Parse(telegram.Parameters[(byte) ParameterCodes.PeerId].ToString());

            ClientPeer peer =
                ClientPeerRegistry.GetClientPeer(guid)
                    as ClientPeer;

            if (peer != null)
            {
                Logger.InfoFormat("Found requesting peer with id={0} to send response", peer.PeerId);

                peer.SendOperationResponse(
                    new OperationResponse(telegram.Code)
                    {
                        ReturnCode = response.ReturnCode,
                        DebugMessage = response.DebugMessage
                    },
                    new SendParameters());
            }
            return true;
        }
    }
}
